#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#
require "../link_parser"

module Luce
  class LinkReferenceDefinitionSyntax < BlockSyntax
    def pattern : Regex
      Luce.link_reference_definition_pattern
    end

    def can_end_block?(parser : BlockParser) : Bool
      false
    end

    def parse(parser : BlockParser) : Node?
      lines = [parser.current] of Line
      parser.advance

      until BlockSyntax.at_block_end?(parser)
        lines << parser.current
        parser.advance
      end

      unless parse_link_reference_definition(lines, parser)
        parser.retreat_by(lines.size)
      end

      nil
    end

    private def parse_link_reference_definition(lines : Array(Line), parser : BlockParser) : Bool
      link_parser = LinkParser.new(lines.map(&.content).join("\n"))
      link_parser.parse_definitions

      return false unless link_parser.valid?

      # Retreat the parsing position back to where the link reference definition
      # ends, so that the next syntax can continue parsing from there.
      parser.retreat_by(link_parser.unconsumed_lines)

      # ameba:disable Lint/NotNil
      label_string = Luce.normalize_link_label(link_parser.label.not_nil!)

      unless parser.document.link_references.has_key?(label_string)
        parser.document.link_references[label_string] = LinkReference.new(label_string,
          # ameba:disable Lint/NotNil
          link_parser.destination.not_nil!,
          link_parser.title)
      end

      true
    end
  end
end
